function Promise(task){
    let that = this
    that.status = 'pending' //默认状态为pending
    that.value = undefined // 成功后的结果
    // 存放所有成功的回调函数
    that.onResolvedCallbacks = [];
    // 存放所有失败的回调函数
    that.onRejectedCallbacks = []

    // 调用次方法可以转换成功态
    function resolve(val){
        // 如果是初始态，则转成成功态
        if(that.status == 'pending'){
            that.status == 'fulfilled'
            that.value = val
            that.onResolvedCallbacks.forEach(item => item(val))
        }
    }

    // 调用次方法可以转换失败态
    function reject(val){
        if (that.status == 'pending'){
            that.status = 'rejected'
            that.value = val
            that.onRejectedCallbacks.forEach(item => item(val))
        }
    }

    try{
        task(resolve, reject);
    }catch(e){
        reject(e)
    }
    

}

// 成功的回调 和 失败的回调
Promise.prototype.then = function(onFulfilled, onReject){
    let that = this
    if(that.status == 'fulfilled'){
        onFulfilled(that.value)
    }
    if(that.status == 'rejected'){
        onReject(that.value)
    }
    if(that.status == 'pending'){
        that.onResolvedCallbacks.push(onFulfilled)
        that.onRejectedCallbacks.push(onReject)
    }
    return that
}

module.exports = Promise


